package com.foogui.faw.oa;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.foogui.common.exception.BizException;
import com.foogui.common.model.Result;
import com.foogui.faw.oa.dto.StartProcessDTO;
import com.foogui.faw.openapi.BaseApiGatewayService;
import com.foogui.faw.openapi.HttpUtil;
import com.foogui.faw.openapi.JsonUtil;
import com.foogui.faw.openapi.UcgConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author ：sunrenlong
 * @description：调用工作流service
 * @date ：Created in 2023/7/1 16:48
 * @version: $
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProcessService {

    private static final String TARGET_URL = "/JT/SA/SA-0214/RWG/instance/transmissionLighthouse?access_token=";

    @Autowired
    private UcgConfig ucgConfig;

    @Autowired
    private BaseApiGatewayService baseApiGatewayService;

    /**
     * 获取审批流程的url
     */
    private final static String START_PROCESS_URL = "/JT/BA/BA-0222/BPM/BPM/startProcessByTemplateName?access_token=";


    /**
     * api开启审批流
     *
     * @param request 要求
     * @return {@link String}
     */
    public String startProcess(StartProcessDTO request) {

        String token = baseApiGatewayService.getToken();
        // 调用接口
        log.info("ProcessService.startProcess.request: {}", request);

        String response = HttpUtil.sendPostFlow(ucgConfig.getHost() + START_PROCESS_URL + token, BeanUtil.beanToMap(request), ContentType.APPLICATION_JSON);

        log.info("ProcessService.startProcess.response: {}", response);


        if (StringUtils.isBlank(response)) {
            log.error("ProcessService.startProcess.response is unexpected {}",response);
        }

        // 处理数据
        Result<JSONObject> result = JsonUtil.jsonToObject(response, new TypeReference<Result<JSONObject>>() {
        });

        if (Objects.isNull(result)) {
            log.error("ProcessService.startProcess.failed.message.null");
            throw new BizException("启动流程失败！");
        }
        if (!Objects.equals(result.getCode(), 200)) {
            log.error("ProcessService.startProcess.failed.message: {}", result.getMessage());
            throw new BizException(result.getMessage());
        }

        return result.getData().get("processInstanceId").toString();
    }

}
